import kk from 'kokos'

cc.Class({
    extends: cc.Component,

    onLoad() {
        const event = kk.event
        const eventEnum = kk.constant.EVENT
        event.on(eventEnum.refreshGold, this.refreshGoldView, this)

        this.lastGold = 0
        this.awardValue = 100

        this.refreshGoldView()
    },

    onDestroy() {
        const event = kk.event
        const eventEnum = kk.constant.EVENT
        event.off(eventEnum.refreshGold, this.refreshGoldView, this)
    },

    // 减金币的动画
    playSubGoldAction() {
        return new Promise((resolve, reject) => {
            const icon = this.node.getChildByName('icon_gold')
            const newIcon = cc.instantiate(icon)
            const iconAction = kk.action.iconJumpAction()
            const finished = cc.callFunc(() => {
                newIcon.destroy()
                resolve()
            }, this)
            const allSeq = cc.sequence(iconAction, finished)

            newIcon.parent = icon
            newIcon.setPosition(0, 0)

            newIcon.runAction(allSeq)
        })
    },

    // 金币变化的时候播放的动画
    playChangeGoldAction() {
        const icon = this.node.getChildByName('icon_gold')
        const action = kk.action.windowOpenAction()

        icon.runAction(action)
    },

    // 刷新金币数值显示
    refreshGoldView() {
        const goldLabel = this.node.getChildByName('label').getComponent(cc.Label)
        const gold = kk.baseData.getGold()

        if (gold !== this.lastGold) {
            this.playChangeGoldAction()
        }
        this.lastGold = gold

        goldLabel.string = gold
    },

    handleAdd() {

    },

    // update (dt) {},
});